package org.finesys.samples.netty.websocket.client;

import static org.finesys.common.netty.websocket.constants.HandlerName.BUFF_WEBSOCKET_Decoder;
import static org.finesys.common.netty.websocket.constants.HandlerName.BUFF_WEBSOCKET_Encoder;
import static org.finesys.common.netty.websocket.constants.HandlerName.HTTP_AGGREGATOR;
import static org.finesys.common.netty.websocket.constants.HandlerName.HTTP_CODEC;
import static org.finesys.common.netty.websocket.constants.HandlerName.STOMP_AGGREGATOR;
import static org.finesys.common.netty.websocket.constants.HandlerName.STOMP_DECODER;
import static org.finesys.common.netty.websocket.constants.HandlerName.STOMP_ENCODER;
import static org.finesys.common.netty.websocket.constants.WebConfigConstant.MAX_FRAME_SIZE;

import org.finesys.common.netty.websocket.stomp.codec.ByteBufToWebSocketFrameEncoder;
import org.finesys.common.netty.websocket.stomp.codec.WebSocketFrameToByteBufDecoder;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.stomp.StompSubframeAggregator;
import io.netty.handler.codec.stomp.StompSubframeDecoder;
import io.netty.handler.codec.stomp.StompSubframeEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class StompClientInitializer extends ChannelInitializer<Channel> {

    @Override
    protected void initChannel(Channel channel) throws Exception {

        ChannelPipeline pipeline =channel.pipeline();
        // 添加HTTP编解码器
        pipeline.addLast(HTTP_CODEC, new HttpServerCodec());
        // 添加HTTP对象聚合器，设置最大消息大小为65536字节
        pipeline.addLast(HTTP_AGGREGATOR, new HttpObjectAggregator(MAX_FRAME_SIZE.getValue()));
        // 添加分块写处理器
        pipeline.addLast(new ChunkedWriteHandler());
        //Websocket Handler配置

        pipeline.addLast(BUFF_WEBSOCKET_Decoder, new WebSocketFrameToByteBufDecoder());
        pipeline.addLast(BUFF_WEBSOCKET_Encoder, new ByteBufToWebSocketFrameEncoder());
        //StompHandler配置
        //stomp协议解码器
        pipeline.addLast(STOMP_DECODER, new StompSubframeDecoder());
        //stomp协议编码器
        pipeline.addLast(STOMP_ENCODER, new StompSubframeEncoder());
        //stomp aggrelator
        pipeline.addLast(STOMP_AGGREGATOR, new StompSubframeAggregator(MAX_FRAME_SIZE.getValue()));
        pipeline.addLast(new StompClientHandler());
    }
}
